
(function($){
	$.extend({
		
		//----------------日期相关-----------------start------------------
		// 日期型的时间格式化
		dateFormat:function(inputDate,formatter) {
		    var date = {
		       "M+": inputDate.getMonth() + 1,
		       "d+": inputDate.getDate(),
		       "h+": inputDate.getHours(),
		       "m+": inputDate.getMinutes(),
		       "s+": inputDate.getSeconds(),
		       "q+": Math.floor((inputDate.getMonth() + 3) / 3),
		       "S+": inputDate.getMilliseconds()
		    };
		    if (/(y+)/i.test(formatter)) {
		    	formatter = formatter.replace(RegExp.$1, (inputDate.getFullYear() + '').substr(4 - RegExp.$1.length));
		    }
		    for (var k in date) {
		       if (new RegExp("(" + k + ")").test(formatter)) {
		    	   formatter = formatter.replace(RegExp.$1, RegExp.$1.length == 1
		              ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
		       }
		    }
		    return formatter;
		},
		
		
		// 时间戳型的时间格式化
		timestampFormat:function(timestamp,formatter){
			formatter =(!formatter)?'yyyy-MM-dd hh:mm:ss':formatter; 
			if(!timestamp) return "";
			var date = new Date();
			date.setTime(timestamp);
			return $.dateFormat(date,formatter);
		},

		// 转为可读格式时间
		timestampFormatReadable:function( timestamp ) {
		    function zeroize( num ) {
		        return (String(num).length == 1 ? '0' : '') + num;
		    }

		    var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
		    
		    var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

		    var curDate = new Date( curTimestamp * 1000 ); // 当前时间日期对象
		    var tmDate = new Date( timestamp * 1000 );  // 参数时间戳转换成的日期对象

		    var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
		    var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();

		    if ( timestampDiff < 60 ) { // 一分钟以内
		        return "刚刚";
		    } else if( timestampDiff < 3600 ) { // 一小时前之内
		        return Math.floor( timestampDiff / 60 ) + "分钟前";
		    } else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
		        return '今天' + zeroize(H) + ':' + zeroize(i);
		    } else {
		        var newDate = new Date( (curTimestamp - 86400) * 1000 ); // 参数中的时间戳加一天转换成的日期对象
		        if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
		            return '昨天' + zeroize(H) + ':' + zeroize(i);
		        } else if ( curDate.getFullYear() == Y ) {
		            return  zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
		        } else {
		            return  Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
		        }
		    }
		},
		
		// 获取当前时间
		nowDatetime: function() {
	    	var nowDate = new Date();
	    	//获取当前年
	    	var year=nowDate.getFullYear();
	    	//获取当前月
	    	var month=nowDate.getMonth()+1;
	    	//获取当前日
	    	var date=nowDate.getDate(); 
	    	var h=nowDate.getHours();       //获取当前小时数(0-23)
	    	var m=nowDate.getMinutes();     //获取当前分钟数(0-59)
	    	var s=nowDate.getSeconds();  
	    	var fillTime = function (s) {
	    	    return s < 10 ? '0' + s: s;
	    	}
	    	return year+'-'+fillTime(month)+"-"+fillTime(date)+"T"+fillTime(h)+':'+fillTime(m)+":"+fillTime(s);
	     },
		
	    // 获取Input组件的时间
		datetimeInputVal:function($input){
			//2018-10-14 16:01
			var val = $input.val();
			if(val.length == 16){
				val = val+":00";
			}
			return val;
		},
		
		// 根据毫秒数获取可读的持续时间
		duration:function(runtime) {
			if(runtime<0){
				return "0s";
			}
			var day = 0, hour = 0, minute = 0, second = 0;
			day = parseInt(runtime / (24 * 3600 * 1000));
			hour = parseInt((runtime - day * 24 * 3600 * 1000) / (3600 * 1000));
			minute = parseInt((runtime - day * 24 * 3600 * 1000 - hour * 3600 * 1000)
					/ (60 * 1000));
			second =  parseInt((runtime - day * 24 * 3600 * 1000 - hour * 3600 * 1000- minute * 60 * 1000)
					/ 1000);
			var str = "";
			if (day > 0) {
				str += day + "d:";
			}
			if(day > 0 || hour > 0){
				str += hour + "h:";
			}
			if(day > 0 || hour > 0 || minute >0){
				str += minute + "m:";
			}
			if(day > 0 || hour > 0 || minute >0 || second >= 0){
				str += second + "s:";
			}
			
			return str.substring(0,str.length-1);
		},
		

		dateStrToStamp: function(string) {
            var f = string.split(' ', 2);
            var d = (f[0] ? f[0] : '').split('-', 3);
            var t = (f[1] ? f[1] : '').split(':', 3);
            return (new Date(
                parseInt(d[0], 10) || null,
                (parseInt(d[1], 10) || 1) - 1,
                parseInt(d[2], 10) || null,
                parseInt(t[0], 10) || null,
                parseInt(t[1], 10) || null,
                parseInt(t[2], 10) || null
                )).getTime()/1000;
        },
		
		//----------------日期相关-----------------end--------------------
		
		
		//----------------String相关-----------------start--------------------
		// 字符串全部替换
		replaceAll : function(str,originalStr,replaceStr){
		    var reg=new RegExp(originalStr,"g");    
		    return str.replace(reg,replaceStr); 
		},
		
		
		// 将字节格式化可读大小
		formatBytes : function(bytes){
			if(bytes == 0){
				return '0B';
			}
			var k = 1024;
			
			var sizes = ['B','KB','MB','GB','TB','PB'];
			var i = Math.floor(Math.log(bytes)/Math.log(k));
			return (bytes/Math.pow(k,i)).toFixed(2)+''+sizes[i];
		},
		
		//将list转换为，分割的字符串
		listToStr : function (list,splitor){
			var str = "";
			$(list).each(function(i,item){
				str = str + item+splitor;
			});
			str = str.substring(0,str.length-1);
			return str;
		},
		
		// 获取UUID
		uuid: function (len, radix) {
			var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
		    var chars = CHARS, uuid = [], i;
		    radix = radix || chars.length;
	
		    if (len) {
		      // Compact form
		      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
		    } else {
		      // rfc4122, version 4 form
		      var r;
	
		      // rfc4122 requires these characters
		      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		      uuid[14] = '4';
	
		      // Fill in random data.  At i==19 set the high bits of clock sequence as
		      // per rfc4122, sec. 4.1.5
		      for (i = 0; i < 36; i++) {
		        if (!uuid[i]) {
		          r = 0 | Math.random()*16;
		          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
		        }
		      }
		    }
	
		    return uuid.join('');
		  },
		//----------------String相关-----------------end--------------------

		//----------------number相关-----------------start------------------
		// 格式化阅读次数
		formatNumer:function(number){
			if(number > 10000){
				return (number/10000).toFixed(1)+"w";
			}
			return number;
		},


		
		//----------------table操作相关-----------------start------------------
		// 获取check表格的选中ID
		getCheckTableSelectIds:function($table){
			var selectIds = [];
			var $checkboxs = $table.find("tbody input[name='tableCheckbox']:checked");
			if($checkboxs.length <= 0 ){
				return selectIds;
			}
			
			$checkboxs.each(function(i,item){
				var value = $(item).attr("value");
				selectIds.push(value);
			});
			return selectIds;
		},
		
		// 设置checktable的选中ID
		setCheckTableSelectIds:function($table,selectIds){
			$.each(selectIds,function(i,item){
				$table.find("tbody input[name='tableCheckbox'][value='"+item+"']").prop("checked",true);
			});
		},
		//----------------table操作相关-----------------end--------------------------
		
		
		//----------------ajax操作相关-----------------start------------------------
		//ajax请求删除
		btnAjaxDeleteAsyn :function($thisBtn,$table,url,successFun,initParam){
			$.btnAjaxComfirmAsyn($thisBtn,$table,'删除',url,successFun,initParam);
		},
		
		
		// 基于按钮的表格确认提交异步请求，至少一条的确认操作
		btnAjaxComfirmAsyn:function ($thisBtn,$table,eventName,url,successFun,initParam){
			var selectIdsList = $.getCheckTableSelectIds($table);
			var argumentLength = arguments.length;
			
			if(selectIdsList == null || selectIdsList.length <= 0 ){
				$.appAlert('请至少选中一条！')
				return;
			}
			
			$.confirm("是否"+eventName+"?共"+selectIdsList.length+"条。",function(){
				var params;
				if(argumentLength == 5){
					params = {"ids":$.listToStr(selectIdsList,',')};
				}else if(argumentLength == 6){
					params = initParam;
					if(params == null) params = {};
					params['ids'] = $.listToStr(selectIdsList,',');
				}
				
				
				$.btnAjaxAsyn($thisBtn,url,params,successFun);
			});
		},
		
		
		// 基于按钮的表格直接提交异步请求
		btnAjaxCommitAsyn:function($thisBtn,$table,url,successFun,initParam){
			var selectIdsList = $.getCheckTableSelectIds($table);
			var argumentLength = arguments.length;
			if(selectIdsList == null || selectIdsList.length <= 0 ){
				$.appAlert('请至少选中一条！')
				return;
			}
			
			var params;
			if(argumentLength == 4){
				params = {"ids":$.listToStr(selectIdsList,',')};
			}else if(argumentLength == 5){
				params = initParam;
				if(params == null) params = {};
				params['ids'] = $.listToStr(selectIdsList,',');
			}
			
			$.btnAjaxAsyn($thisBtn,url,params,successFun);
		},
		
		
		// 基于按钮点击的的ajax异步请求事件
		btnAjaxAsyn:function($thisBtn,url,params,successFun,failFun){
			$thisBtn.addClass("loading disabled");
			var callBack = function(){
				$thisBtn.removeClass("loading disabled");
			};
			
			$.ajaxBase(url,params,callBack,successFun,failFun,null);
		},
		
	
		//用于文件上传的异步请求事件
		btnAjaxUploadAsyn:function ($thisBtn,url,params,successFun,failFun){
			$thisBtn.addClass("loading disabled");
			var callBack = function(){
				$thisBtn.removeClass("loading disabled");
			};
			var otherSettings = {
				contentType:false,
				processData:false,
			};
			$.ajaxBase(url,params,callBack,successFun,failFun,otherSettings);
		},
		
		//ajax同步请求
		ajaxSyn:function(url,params,successFun,failFun){
			var otherSettings = {async : false};
			$.ajaxBase(url,params,null,successFun,failFun,otherSettings);
		},
		
		//ajax异步请求
		ajaxAsyn:function (url,params,successFun,failFun){
			$.ajaxBase(url,params,null,successFun,failFun,null);
		},
		
		
		ajaxBase:function(url,params,callBack,successFun,failFun,otherSettings){
			// 默认参数
			var defaults = {
				type : 'post',
				url : url,
				data : params,
				success : function(result) {
					if(callBack){
						callBack(result);
					}
					
					if (result.code === 0) {
						if(successFun){
							successFun(result.data);
						}
					} else {
						
						
						// 保存失败
						if(failFun){
							failFun(result);
						}else{
							$.appAlert("提示："+result.message);
						}
					}
				}
			};
			
			// 参数合并
			var settings =$.extend(true,defaults,otherSettings);
			
			// 执行异步请求
			$.ajax(settings);
		},
		
		
		ajaxGet:function(url,callback){
			var settings = {
				type : 'get',
				url : url,
				data : null,
				dataType: "jsonp",
				success : function(result) {
					if(callback){
						callback(result);
					}
				}
			};
			
			
			// 执行异步请求
			$.ajax(settings);
		},
		//----------------ajax操作相关-----------------end------------------------
		
		
		//----------------popWin操作相关---------------start------------------------	
		//打开弹出窗口
		openPopWin:function ($win,onShowFun,onHideFun){
			var argumentLength = arguments.length;
			if(argumentLength == 1){
				$win.modal({
					closable:false,
					allowMultiple:true,
					duration:250,
					onHidden:function(){
					}
				}).modal('show');
			}else if(argumentLength == 2){
				$win.modal({
					closable:false,
					allowMultiple:true,
					onShow:function(){
						if(onShowFun != null){
							onShowFun();
						}
					},
					onHidden:function(){
					}
				}).modal('show');
			}else if(argumentLength == 3){
				$win.modal({
					closable:false,
					allowMultiple:true,
					onShow:function(){
						if(onShowFun != null){
							onShowFun();
						}
					},
					onHidden:function(){
						if(onHideFun != null){
							onHideFun();
						}
					}
				}).modal('show');
			}
		},
		
		// 隐藏弹出窗口
		hidePopWin : function($win,onHideFun){
			$win.modal({
				onHidden:function(){
					if(onHideFun != null){
						onHideFun();
					}
				}
			}).modal('hide');
		},
		
		
		//主要用于转向修改界面等
		btnOpenAjaxWinByTable : function($thisBtn,$table,$win,url,successFun){
			var selectIdsList = $.getCheckTableSelectIds($table);
			if(selectIdsList == null || selectIdsList.length != 1 ){
				$.appAlert('只能选中一条，目前选择了'+selectIdsList.length+'条！')
				return;
			}
			var params = {"id":$.listToStr(selectIdsList,',')};
			$.openPopWin($win,function(){
				$.btnAjaxAsyn($thisBtn,url,params,successFun);
			});
			
		},
		
		
	
		//----------------popWin操作相关-----------------end------------------------
		
		//----------------弹窗相关---------------------start------------------------
		// 警告弹窗
		appAlert : function(msg,okFunc){
			$.alert({
				animation: 'scale',
   				closeAnimation: 'rotateXR',
			    title: '提示',
			    closeIcon: true,
			    type: 'red',
			    content: msg
			});
		},
		
		
		// Loading弹窗
		loading : function (msg){
			var $systemLoadingWin = $('<div class="ui mini modal" style="left:70%;width: auto">'+
										'	<div class="content" style="background: white;">'+
										'	<p style="float: left;position: relative;top: -8px;" class="message"></p>'+
										'</div>'+
									'</div>');
			$systemLoadingWin.find('.message').text(msg);
			$.openPopWin($systemLoadingWin);
			return $systemLoadingWin;
		},
		
		// 取消loading弹窗
		stopLoading : function ($win,closeFunc){
			$.hidePopWin($win,function(){
				$win.remove();
				if(closeFunc != null){
					closeFunc();
				}
			});
		},
		
		// 确认弹窗
		appConfirm : function (msg,yesCallback,noCallback){
			$.confirm({
				animation: 'scale',
				closeIcon: true,
   				closeAnimation: 'rotateXR',
			    title: '提示',
			    content: msg,
			    type: 'orange',
			    buttons: {
			        confirm: {
			            text: '确定',
			            btnClass: 'btn-blue',
			            action: function(){
			            	if(yesCallback){
			            		yesCallback();
			            	}
			            }
			        },
			        close: {
			        	text: '取消',
			        	action:function () {
				        	if(noCallback){
			            		noCallback();
			            	}
				        }
			        }
			    }
			});
		},
		
		
		// 提示弹窗
		tip : function (color,msg,yesCallback){
			$.confirm({
				animation: 'scale',
				closeIcon: true,
   				closeAnimation: 'rotateXR',
			    title: '提示',
			    content: msg,
			    type: color,
			    buttons: {
			        confirm: {
			            text: '确定',
			            btnClass: 'btn-blue',
			            action: function(){
			            	if(yesCallback){
			            		yesCallback();
			            	}
			            }
			        }
			    }
			});
		},
		
		//----------------弹窗相关---------------------end------------------------
		
		//----------------Select组件初始化---------------------start------------------------
		initSelect : function ($select,list,key,value,selectedVal,defaultTag){
			$select.empty();
			if(defaultTag != null && defaultTag !=''){
				$('<option value="">'+defaultTag+'</option>').appendTo($select);
			}
			$(list).each(function(i,item){
				$('<option value="'+item[key]+'">'+item[value]+'</option>').appendTo($select);
			})
			
			if(selectedVal != null && selectedVal != ''){
				$select.val(selectedVal);
			}
		}
		
		//----------------其他操作---------------------end------------------------
	});
})(jQuery)